from SocketServer import TCPServer, StreamRequestHandler, ThreadingMixIn
import threading
import os


class CmdServer(ThreadingMixIn, TCPServer):
    allow_reuse_address = True


class Handler(StreamRequestHandler):

    users = {}
    rootPath = "/home/shenyuan"

    def handle(self):
        addr = self.request.getpeername()
        self.wfile.write("connected\n")
        rec = self.rfile.readline().split()
        if rec[0] == "data":
            dataport = int(rec[1])
            Handler.users[addr[0], dataport] = addr[1]
            self.Transfer()
        else:
            Handler.users[addr] = ""
            self.Cmd()
        # if addr not in Handler.users.keys():
        #     if addr in Handler.users.values():
        # receive file
        #         pass
        #     else:
        # new connection
        #         Handler.users[addr] = ""
        #         self.Cmd(addr)

        # else:
        # cmd transport
        #     self.Cmd(addr)

        # if addr in Handler.users.keys():
        #     del Handler.users[addr]
        self.request.close()

    def Cmd(self):
        addr = self.request.getpeername()
        while True:
            try:
                cmd = self.rfile.readline().strip()
                print "{}:{}".format(addr, cmd)
                cmd = cmd.split()
                if cmd[0] == "ls":
                    realpath = Handler.rootPath + cmd[1]
                    if os.path.isdir(realpath):
                        data = os.listdir(realpath)
                        data = [f for f in data if f[0] != "."]
                        if os.path.normpath(realpath) != os.path.normpath(Handler.rootPath):
                            data.insert(0, "..")
                    else:
                        data = cmd[1][:-1]
                        print data
                    self.wfile.write(repr(data))
            except:
                self.request.close()
                break
        self.request.close()
        del Handler.users[addr]

    def Transfer(self):
        addr = self.request.getpeername()
        while True:
            try:
                request = self.rfile.readline().strip()
                print "{}:{}".format(addr, request)
                realfile = Handler.rootPath+os.sep+request.split()[1]
                print realfile
                if os.path.isfile(realfile):
                    self.wfile.write(open(realfile).read())
            except:
                self.request.close()
                break

        self.request.close()


server = CmdServer(('', 1234), Handler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.deamon = True
server_thread.start()
